package com.cyou.nad.utils;

import org.apache.commons.lang.StringUtils;


/** 
 * @author 李剑 E-mail: lijian@sohu-rd.com 
 * @version 创建时间：Jun 25, 2009 10:38:18 AM  
 */
public class StringDataUtils {
	
	/**
	 * 计算字符串的字节数，中文，全角按照2个字节计算
	 * @param string
	 * @return
	 */
	public static int getStrByteLen(String string){
		if(null == string){
			return 0;
		}
		char[] chars = string.toCharArray();
		int len = 0;
		for(char c : chars){
			if(c < 256){
				len ++;
			}else{
				len += 2;
			}			
		}
		return len;
	}
	
	/**
	 * 按照字节截断字符串长
	 * @param string
	 * @param maxByteLen
	 * @return
	 */
	public static String getFirstSubStringByByteLen(String string, int maxByteLen){
		if(null == string || string.length() < 1){
			return string;
		}
		
		if(string.length() * 2 < maxByteLen){
			return string;
		}
		
		char[] chars = string.toCharArray();		
		StringBuffer subString = new StringBuffer();
		int len = 0;
		for(char c : chars){
			if(c < 256){
				len ++;
			}else{
				len += 2;
			}
			if(len <= maxByteLen){
				subString.append(c);
			}else{
				break;
			}
		}		
		return subString.toString();
	}
	
	/**
     * 转义like语句中的_和%
     */
    public static String escapeSQLLike(String likeStr) {
    	String str = StringUtils.replace(likeStr, "/",    "//");
        str = StringUtils.replace(str, "_", "/_");
        str = StringUtils.replace(str, "%",    "/%");
        
        return str;
    }
	
	public static void main(String[] strings){
		String str = "1我a在b做c测d试";
		for(int i=0;i<20;i++){
			System.out.println(i + ":" + getFirstSubStringByByteLen(str,i));
		}
	}
}
